const http = {
	baseUrl: 'http://127.0.0.1:9091',
	request(config) {
		//config : 请求配置对象，具体的值参照uniapp文档 
		config = beforeRequest(config)
		config.url = this.baseUrl + config.url
		//创建一个Promise对象，在里面发送请求
		return new Promise((resolve, reject) => {
			uni.request(config).then(res => {
				let [error, resp] = res
				const response = beforeResponse(resp)
				resolve(response)
			}).catch(err => {
				errorHandle()
				reject(err)
			})
		})
	},
	get(url, params, auth) {
		/**
		 * url:接口地址
		 * data:查询参数
		 * auth:请求是否需要携带token进行认证（true or false）
		 */
		return this.request({
			url: url,
			data: params,
			method: "GET",
			auth: auth
		})
	},
	delete(url, auth) {
		return this.request({
			url: url,
			method: "DELETE",
			auth: auth
		})
	},
	post(url, data, auth) {
		return this.request({
			url: url,
			data: data,
			method: "POST",
			auth: auth
		})
	},
	put(url, data, auth) {
		return this.request({
			url: url,
			data: data,
			method: "PUT",
			auth: auth
		})
	}
}
//请求拦截器
const beforeRequest = (config) => {
	//请求之前做的操作
	console.log('请求拦截器')
	config.header = {}
	if(config.auth){
		console.info(uni.getStorageSync("token"))
		if(uni.getStorageSync("token")){
			//在请求头中添加上token
			config.header['Authorization'] = 'Bearer ' + uni.getStorageSync("token")
		}else{
			//则说明没有权限去登录
			uni.navigateTo({
				url:'/pages/personal/login'
			})
		}
	}
	return config;
}
//响应拦截器
const beforeResponse = (response) => {
	//服务返回后做的处理
	console.log('响应拦截器')
	// if(response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204 &&  response.data.code != 200){
	if(response.data.code != 200){
		console.info(response)
		if(response.data.message){
			uni.showToast({
				title:response.data.message.toString(),
				duration: 2000,
				icon:"error",
			})
		}
	}
	return response.data;
}
//异常处理器
const errorHandle = (err) => {
	console.log('网络异常，请求失败', err)
}

export default http